const axios = require("axios");
const query = require("../../utils/query");
const { BAIDU_CLIENT_ID, BAIDU_CLIENT_SECRET } = require("../../config");
 async function convertPcmToText(pcmBuffer) {
  const sql = `SELECT * FROM tokens WHERE name = 'voice_token' LIMIT 1`;
  const result = await query(sql);
  const token = result[0].access_token; // 获取百度语音 API 的 Access Token

  const base64Audio = pcmBuffer.toString("base64"); // Base64 编码音频数据
  const len = pcmBuffer.length; // PCM 数据的字节长度

  try {
    const response = await axios.post(
      "https://vop.baidu.com/pro_api",
      {
        format: "pcm", // 音频格式为 pcm
        rate: 16000, // 采样率，pcm 音频的常用采样率是 16000
        token: token, // 获取的百度 API token
        speech: base64Audio, // 音频数据的 Base64 编码
        client_id: BAIDU_CLIENT_ID,
        client_secret: BAIDU_CLIENT_SECRET,
        len: len, // 音频数据的字节长度
        cuid: BAIDU_CLIENT_ID,
        channel: 1,
        dev_pid: 80001
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    console.log('response-response:',response)
    // 处理返回的语音识别结果
    if (response.data.err_no === 0) {
      console.log("识别结果：", response.data.result[0]);
      return response.data.result[0]; // 返回转录的文本
    } else {
      console.error("语音识别失败:", response.data.err_msg);
      throw new Error("语音识别失败");
    }
  } catch (error) {
    console.error("请求百度语音 API 失败:", error);
    throw error;
  }
}

module.exports = convertPcmToText;
